#include <QtGui>
#include "contactlisttab.h"

const static int MIN_ROWS = 17;
const static int COLUMN = 2;
const static int WIDTH_IP = 200;
const static int WIDTH_NAME = 330;
const static int LINE_HEIGHT = 20;
const static int COL_INDEX_IP = 0;
const static int COL_INDEX_NAME = 1;
const static QString IP_DESCRIPTION = QObject::tr("IP");
const static QString USER_NAME_DESCRIPTION = QObject::tr("User Name");

ContactListTab::ContactListTab(QWidget *parent) :
    QTableWidget(MIN_ROWS, COLUMN, parent)
{
    setColumnWidth(COL_INDEX_IP, WIDTH_IP);
    setColumnWidth(COL_INDEX_NAME, WIDTH_NAME);

    setSelectionBehavior(QAbstractItemView::SelectRows);
    setSelectionMode(QAbstractItemView::SingleSelection);
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    QStringList header;
    header.append(IP_DESCRIPTION);
    header.append(USER_NAME_DESCRIPTION);
    setHorizontalHeaderLabels(header);

    connect(this, SIGNAL(cellDoubleClicked (int, int)),
            this, SLOT(rowDoubleClicked(int)));
}

void ContactListTab::updateContactList(const QList<userInfo> &contactList)
{
    mContactList.clear();
    mContactList.append(contactList);

    clearContents();

    int length = contactList.size();
    setRowCount(std::max(MIN_ROWS, length));

    for (int index = 0; index < length; ++index)
    {
        QTableWidgetItem *ip = new QTableWidgetItem(contactList[index].getIp());
        QTableWidgetItem *name = new QTableWidgetItem(contactList[index].getName());
        setItem(index, COL_INDEX_IP, ip);
        setItem(index, COL_INDEX_NAME, name);
    }

    for (int index = 0; index < std::max(columnCount(), MIN_ROWS); ++index) {
        setRowHeight(index, LINE_HEIGHT);
    }
}

void ContactListTab::rowDoubleClicked(int row)
{
    QTableWidgetItem *ipItem = item(row, COL_INDEX_IP);
    if (0 != ipItem)
    {
       emit openConversationTab(ipItem->text());
    }
}

QString ContactListTab::findUserNameByIp(const QString &ip)
{
    for (int index = 0; index < mContactList.size(); ++index)
    {
        if (ip == mContactList[index].getIp())
        {
            return mContactList[index].getName();
        }
    }
    return ip;
}
